package com.buaa.annotation.security.handler;

import com.buaa.annotation.common.ResponseCode;
import com.buaa.annotation.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        ResponseCode code = ResponseCode.ACCESS_DENIED;
        String msg = String.format("请求访问：%s，您的权限不足", request.getRequestURI());
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(new ObjectMapper().writeValueAsString(ResultModel.error(code, msg)));
    }
}
